<template>
  <div class="conversation-container">
    <div class="conversation-lists">
      <!-- 待接入列表 -->
      <div class="conversation-list left-list">
        <div class="conversation-list-item">
          <div class="conversation-list-title">待接入 {{ pendingConversations.length }}</div>
          <div class="conversation-list-body">
            <router-link
              tag="div" :to="chat(conversation)" replace
              v-for="(conversation, key) in pendingConversations" :key="key"
            >
              <div class="conversation-item">
                <div class="conversation-item-head">
                  <img :src="conversation.data.avatar" class="conversation-item-avatar"/>
                </div>
                <div class="item-info">
                  <div class="item-info-name">{{ conversation.data.name }}</div>
                  <div v-if="conversation.lastMessage.type === 'text'" class="item-info-message">
                    {{ conversation.lastMessage.payload.text }}
                  </div>
                  <div v-else-if="conversation.lastMessage.type === 'image'" class="item-info-message">[图片消息]</div>
                  
                  <div v-else class="item-info-message">[未识别内容]</div>
                </div>
              </div>
            </router-link>
          </div>
        </div>
      </div>
      
      <!-- 已接入列表 -->
      <div class="conversation-list right-list">
        <div class="conversation-list-item">
          <div class="conversation-list-title">已接入 {{ conversations.length }}</div>
          <div v-if="conversations.length" class="conversation-list-body">
            <router-link
              tag="div" :to="chat2(conversation)" replace
              v-for="(conversation, key) in conversations" :key="key"
            >
              <div class="conversation-item" @contextmenu.prevent.stop="e => showRightClickMenu(e,conversation)">
                <div class="conversation-item-head">
                  <img :src="conversation.data.avatar" class="conversation-item-avatar"/>
                  <span v-if="conversation.unread" class="conversation-item-unread">{{ conversation.unread }}</span>
                </div>
                <div class="conversation-item-info">
                  <div class="item-info-top">
                    <div class="item-info-name">{{ conversation.data.name }}</div>
                    <!-- <div class="item-info-time">{{conversation.lastMessage.update_time }}</div> -->
                  </div>
                  <div class="item-info-bottom">
                    <div v-if="conversation.lastMessage.status === 'sending'" class="item-info-sending"></div>
                    <div v-if="conversation.lastMessage.status === 'fail'" class="item-info-failed"></div>
                    <div v-if="conversation.lastMessage.type === 'text'" class="item-info-message">
               
                      {{conversation.lastMessage.payload.text }}
                    </div>
                    <div v-else-if="conversation.lastMessage.type === 'image'" class="item-info-message">[图片消息]</div>

                    <div v-else-if="conversation.lastMessage.type === 'CS_ACCEPT'" class="item-info-message">接入成功</div>
                  
                    <div v-else class="item-info-message">[未识别内容]</div>
                  </div>
                </div>
              </div>
            </router-link>
          </div>
        </div>
      </div>
    </div>
    
    <div v-if="rightClickMenu.visible" :style="{'left': rightClickMenu.x + 'px', 'top': rightClickMenu.y + 'px'}"
         class="action-box">
      <div class="action-item" @click="topConversation">{{ rightClickMenu.conversation.top ? '取消置顶' : '置顶' }}</div>
      <div class="action-item" @click="deleteConversation">删除聊天</div>
    </div>
    
    <div class="conversation-main">
      <router-view :key="$route.params.id"></router-view>
    </div>
  </div>
</template>

<script>
  import { post } from '@/api/request'
import { EventBus } from '../utils/eventBus'
import { formatDate } from '../utils/utils.js'

  export default {
    name: 'Conversation',
    data() {
      return {
        pendingConversations: [],
        conversations: [],
        // Conversation右键菜单
        rightClickMenu: {
          conversation: null,
          visible: false,
          x: null,
          y: null,
        },
        currentAgent: null
      }
    },
    created() {
      document.addEventListener('click', this.hideRightClickMenu);
      // Mock currentAgent data
      this.currentAgent = {
        id: 'agent_001',
        shopId: 'shop_001',
        data: {
          name: '客服小美',
          avatar: 'https://randomuser.me/api/portraits/women/32.jpg'
        }
      };
      this.loadConversations();

      // 每10秒刷新一次消息列表
      this.timer = setInterval(() => {
        this.loadConversations();
      }, 3000);

      // Listen for refresh event
    EventBus.$on('refresh-conversations', this.loadConversations);
      EventBus.$on('loginOut', () => { 
        console.log("退出");
      });
      EventBus.$on('addNotAccess', () => {
        this.loadConversations();
      });
    },
    beforeDestroy() {
      // 清除定时器
      if (this.timer) {
        clearInterval(this.timer);
      }
      // this.goEasy.im.off(this.GoEasy.IM_EVENT.CONVERSATIONS_UPDATED, this.renderLatestConversations);
      // this.goEasy.im.off(this.GoEasy.IM_EVENT.PENDING_CONVERSATIONS_UPDATED, this.renderPendingConversations);
      // Remove event listener
      EventBus.$off('refresh-conversations', this.loadConversations);
    },
    methods: {
      formatDate,
      formatDateTime(dateTimeStr) {
        if (!dateTimeStr) return '';
        const date = new Date(dateTimeStr);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      },
      loadConversations() {

        post('/api/v1/getSessionList', {
          page: 1,
          pageSize: 999
        }).then(res => {
          
          let list = []
          res.result.list_session.forEach(item => {
          console.log(item);
            if (item.userInfo) {
              list.push({
                id: item.session.id,
                unread: item.session.state === 1 ? 1 : 0,
              
              data: {
                name: item.userInfo.nick_name||'未识别',
                avatar:  item.userInfo.image_url || 'https://randomuser.me/api/portraits/women/32.jpg'
              },
              lastMessage: {
                type: 'text',
                payload: {
                  text: this.formatDateTime(item.session.update_time)
                }
              }
            })
             }
          
          })

          let list2 = []
          res.result.access_session.forEach(item => {
            list2.push({
              id: item.session.id,
              data: {
                name: item.userInfo.nick_name,
                avatar:  item.userInfo.image_url || 'https://randomuser.me/api/portraits/women/32.jpg'
              },
              unread: item.session.state === 1 ? 1 : 0,
              lastMessage: {
                type: 'text',
                payload: {
                  text: this.formatDateTime(item.session.update_time) || '未接入'
                },
                update_time: this.formatDateTime(item.session.update_time)
              }
            })
          })
          this.conversations=list2
          
          this.pendingConversations =  list
          console.log(res);
        });



   
      // return
      //   this.goEasy.im.pendingConversations({
      //     onSuccess: (result) => {
      //       this.renderPendingConversations(result.content);
      //     },
      //     onFailed: (error) => {
      //       console.log('获取待接入列表失败, code:' + error.code + 'content:' + error.content);
      //     },
      //   });
      //   this.goEasy.im.latestConversations({
      //     onSuccess: (result) => {
      //       this.renderLatestConversations(result.content);
      //     },
      //     onFailed: (error) => {
      //       console.log('获取已接入列表失败, code:' + error.code + 'content:' + error.content);
      //     },
      //   });
      },
      listenConversationUpdate() {
        // 监听会话列表变化
        this.goEasy.im.on(this.GoEasy.IM_EVENT.CONVERSATIONS_UPDATED, this.renderLatestConversations);
        this.goEasy.im.on(this.GoEasy.IM_EVENT.PENDING_CONVERSATIONS_UPDATED, this.renderPendingConversations);
      },
      renderPendingConversations(content) {
        this.pendingConversations = content.conversations;
      },
      renderLatestConversations(content) {
        this.conversations = content.conversations;
      },
      chat(conversation) {
        if (!conversation || !conversation.id) {
          return { path: '/' };
        }
        // Mark conversation as read when clicked
        this.markConversationAsRead(conversation);
        return {
          path: '/conversations/chat/' + conversation.id,
          query: {
            name: conversation.data.name,
            avatar: conversation.data.avatar,
            status:'pending'
          }
        };
      },
      chat2(conversation) {
        if (!conversation || !conversation.id) {
          return { path: '/' };
        }
        // Mark conversation as read when clicked
        this.markConversationAsRead(conversation);
        return {
          path: '/conversations/chat/' + conversation.id,
          query: {
            name: conversation.data.name,
            avatar: conversation.data.avatar,
            status:'access'
          }
        };
      },
      markConversationAsRead(conversation) {
        // Only mark as read if it was actually unread
        if (conversation.unread > 0) {
          // Mark conversation as read by setting unread to 0
          
          // Send WebSocket message to mark as read
          let ws = null;
          const homeComponent = this.$root.$children.find(child => child.$options.name === 'Home');
          if (homeComponent && homeComponent.ws) {
            ws = homeComponent.ws;
          }
          
          if (!ws && this.$root.$children[0] && this.$root.$children[0].ws) {
            ws = this.$root.$children[0].ws;
          }
          
          if (ws && ws.readyState === WebSocket.OPEN) {
            const readMessage = {
              "session_id": conversation.id,
              "content_type": "read",
              "content": "",
              "ids": []
            };
            console.log('Marking conversation as read:', readMessage);
            ws.send(JSON.stringify(readMessage));
          }
        }
      },
      showRightClickMenu(e, conversation) {
        this.rightClickMenu.conversation = conversation;
        this.rightClickMenu.visible = true;
        this.rightClickMenu.x = e.pageX;
        this.rightClickMenu.y = e.pageY;
      },

      hideRightClickMenu() {
        this.rightClickMenu.visible = false;
      },

      topConversation() {
        let conversation = this.rightClickMenu.conversation;
        let description = conversation.top ? '取消置顶' : '置顶';
        this.goEasy.im.topConversation({
          top: !conversation.top,
          conversation: conversation,
          onSuccess: function () {
            console.log(description, '成功');
          },
          onFailed: function (error) {
            console.log(description, '失败：', error);
          },
        });
      },
      deleteConversation() {
        if (!this.rightClickMenu.conversation.ended) {
          alert("删除失败：会话尚未结束");
          return
        }
        if (confirm('确认要删除这条会话吗？')) {
          this.goEasy.im.removeConversation({
            conversation: this.rightClickMenu.conversation,
            onSuccess: function () {
              console.log('删除会话成功');
            },
            onFailed: function (error) {
              console.log(error);
            },
          });
        }
      }
    }
  }
</script>

<style scoped>
  .conversation-container {
    width: 100%;
    height: 100%;
    display: flex;
    background: #FFFFFF;
  }

  .conversation-lists {
    width: 440px;
    border-right: 1px solid #eee;
    display: flex;
    flex-direction: row;
    padding: 10px;
    position: relative;
  }

  .conversation-list {
    flex: 1;
    display: flex;
    flex-direction: column;
    margin: 0 5px;
  }

  .left-list {
    border-right: 1px solid #f0f0f0;
    padding-right: 10px;
  }

  .right-list {
    padding-left: 10px;
  }

  .conversation-list-title {
    font-size: 15px;
    margin: 5px 10px;
    color: rgba(0, 0, 0, 0.9);
  }

  .conversation-list-body {
    overflow-y: auto;
    max-height: calc(60vh - 50px);
    scrollbar-width: none;
    -ms-overflow-style: none;
  }

  .conversation-list-body::-webkit-scrollbar {
    display: none;
  }

  .action-box {
    width: 100px;
    height: 60px;
    background: #ffffff;
    border: 1px solid #cccccc;
    position: fixed;
    z-index: 100;
    border-radius: 5px;
  }

  .action-item {
    padding-left: 15px;
    line-height: 30px;
    font-size: 13px;
    color: #262628;
    cursor: pointer;
  }

  .action-item:hover {
    background: #dddddd;
  }

  .conversation-item {
    display: flex;
    padding: 10px;
    cursor: pointer;
  }

  .conversation-item-head {
    position: relative;
    margin-right: 5px;
  }

  .conversation-item-avatar {
    width: 40px;
    height: 40px;
    border-radius: 4px;
  }

  .conversation-item-unread {
    position: absolute;
    top: -9px;
    right: -9px;
    width: 18px;
    height: 18px;
    line-height: 18px;
    border-radius: 50%;
    text-align: center;
    color: #fff;
    font-size: 12px;
    background-color: #fa5151;
  }

  .conversation-item-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }

  .item-info-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .item-info-name {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    word-break: break-all;
    font-size: 15px;
    width: 150px;
    line-height: 25px;
    color: #333333;
  }

  .item-info-time {
    color: #666666;
    font-size: 12px;
  }

  .item-info-bottom {
    display: flex;
    align-items: center;
  }

  .item-info-message {
    font-size: 12px;
    line-height: 20px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: 150px;
    color: #606266;
  }

  .item-info-failed {
    background: url("../assets/images/failed.png") no-repeat center;
    background-size: 12px;
    width: 12px;
    height: 12px;
    margin-right: 2px;
  }

  .item-info-sending {
    background: url("../assets/images/pending.gif") no-repeat center;
    background-size: 12px;
    width: 12px;
    height: 12px;
    margin-right: 2px;
  }

  .router-link-active {
    background: #eeeeee;
    border-radius: 5px;
  }

  .conversation-main {
    flex: 1;
    background: #FFFFFF;
  }

</style>
